//
//  NSDate+XHExtension.m
//  Rippton2.0
//
//  Created by 胡旭辉 on 2019/8/23.
//  Copyright © 2019 胡旭辉. All rights reserved.
//

#import "NSDate+XHExtension.h"

@implementation NSDate (XHExtension)


- (NSInteger)getDayWithCurrentDate:(NSDate *)currentDate andSourceDate:(NSDate *)sourceDate{
    
    NSCalendarUnit unit = NSCalendarUnitDay;
    
    NSDateComponents *cmps = [self getComponentsWithCurrentDate:currentDate sourceDate:sourceDate andUnit:unit];
    return cmps.day;
}
- (NSInteger)getHourWithCurrentDate:(NSDate *)currentDate andSourceDate:(NSDate *)sourceDate{
    
    NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    NSDateComponents *cmps = [self getComponentsWithCurrentDate:currentDate sourceDate:sourceDate andUnit:unit];
    return cmps.hour;
}
- (NSInteger)getMinuteWithCurrentDate:(NSDate *)currentDate andSourceDate:(NSDate *)sourceDate{
    
    NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    NSDateComponents *cmps = [self getComponentsWithCurrentDate:currentDate sourceDate:sourceDate andUnit:unit];
    return cmps.minute;
}


- (NSDateComponents *)getComponentsWithCurrentDate:(NSDate *)currentDate sourceDate:(NSDate *)sourceDate andUnit:(NSCalendarUnit)unit{
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    
    NSCalendar *calendar = [NSCalendar calendar];
    
    NSString *timeStr = [sourceDate getTimeWithFormatter:@"yyyy:MM:dd:HH:mm"];
    
    fmt.dateFormat = @"yyyy:MM:dd:HH:mm";
    
    NSDate *createdAtDate = [fmt dateFromString:timeStr];

    NSDateComponents *cmps = [calendar components:unit fromDate:currentDate toDate:createdAtDate options:0];
    
    return cmps;
}

- (NSInteger)getAgeWithBirthday:(NSDate *)birthday{
    NSDate *nowDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /// 获取当前时间
    unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *date = [calendar components:unitFlags fromDate:birthday toDate:nowDate options:0];
    return [date year];
}

@end
